<?php
namespace Common\Model;
use Common\Model\BaseModel;
/**
 * 权限规则model
 */
class OrderModel extends BaseModel{


	/**
	 * 初始化
	 */
	public function __construct(){

	}

	/**
	 * 首页
	 */
	public function index($total_page = 10){

		$total_page = 8;

		$get = I("get.");

		//页码
		$start_page = I("get.p",0,'int');

		//获取订单列表
		$where = array(
			"b.user_id"=>session('user.id')
		);

		//搜索关键词
		if(!empty($get['date_time'])){
			$date_time = explode(" - ",$get['date_time']);
			$get['start_time'] = $date_time[0]." 00:00:00";
			$get['end_time'] = $date_time[1]." 23:59:59";
			$where['a.order_create_time'] = array(array('ELT',$get['end_time']),array('EGT',$get['start_time']),"AND");
			$parameter['start_time'] = $date_time[0];
			$parameter['end_time'] = $date_time[1];
		}

		if($get['typeid'] == 1){
			$get['start_time'] = date("Y-m-d",time())." 00:00:00";
			$get['end_time'] = date("Y-m-d",time())." 23:59:59";
			$where['a.order_create_time'] = array(array('ELT',$get['end_time']),array('EGT',$get['start_time']),"AND");
			$get['date_time'] = date("Y-m-d",time())." - ".date("Y-m-d",time());
			$parameter['start_time'] = date("Y-m-d",time());
			$parameter['end_time'] = date("Y-m-d",time());
		}

		if(!empty($get['keyword'])){
			switch($get['pattern']){
				case 0:
					$where['a.order_phone'] = array('eq',$get['keyword']);
				break;
				case 1:
					$where['a.order_sn'] = array('eq',$get['keyword']);
					break;
				case 2:
					$where['b.goods_id'] = array('eq',$get['keyword']);
					break;
				case 3:
					$where['b.page_name'] = array('like',"%".$get['keyword']."%");
					break;
				case 4:
					$where['b.id'] = array('eq',$get['keyword']);
					break;
				case 5:
					$where['d.package_name'] = array('like',"%".$get['keyword']."%");
					break;
				case 6:
					$where['a.order_address'] = array('like',"%".$get['keyword']."%");
					break;
			}
			$parameter['pattern'] = $get['pattern'];
			$parameter['keyword'] = $get['keyword'];
		}

		if(!empty($get['order_state'])){
			$where['a.order_state'] = array('eq',$get['order_state']);
			$parameter['order_state'] = $get['order_state'];
		}

		if(!empty($get['express_id'])){
			$where['a.express_id'] = array('eq',$get['express_id']);
			$parameter['express_id'] = $get['express_id'];
		}

		$items = M("order")->alias("a")
			->join("LEFT JOIN __ADDPAGE_INFO__ b ON a.addpage_info_id = b.id LEFT JOIN __GOODS__ as c ON b.goods_id = c.id")
			->join("LEFT JOIN __ADDPAGE_PACKAGE__ d ON a.addpage_package_id = d.id")
			->join("LEFT JOIN __EXPRESS__ e ON a.express_id = e.id")
			->field("a.*,b.page_name,c.goods_name,d.package_price,e.express_name")->where($where)->page($start_page,$total_page)->order("a.id desc")->select();

		$list = array();

		//获取当前订单数据
		$repetition_data = $this->repetition_data();

		foreach($items as $k=>$item){

			$list[$k] = $item;

			$list[$k]['be_careful'] = preg_match("/^(?!.*(".$item['order_ip_address'].")).*$/",$item['order_address']);

			$list[$k]['repetition'] = $this->check_repetition($item,$repetition_data);

		}

		$count = M("order")->alias("a")->join("LEFT JOIN __ADDPAGE_INFO__ b ON a.addpage_info_id = b.id LEFT JOIN __GOODS__ c ON b.goods_id = c.id")->where($where)->count();

		$pages = $this->pageClass($count,$total_page);

		//写入缓存
		$province_city_area = F('province_city_area');

		if(empty($province_city_area)){

			//获取初始化全国地址
			$goods_list = M("province_city_area")->select();

			$province_city_area = $this->city_area($goods_list);

			F('province_city_area',$province_city_area);

		}

		//新增订单 - 获取页面名称
		$addpage_info = M("addpage_info")->field("id,page_name")->where("user_id=".session('user.id'))->order("id desc")->select();

		$data = array(
			"items"=>$list,
			"pages"=>$pages,
			"pattern"=>$get['pattern'],
			"keyword"=>$get['keyword'],
			"order_state"=>$get['order_state'],
			"express_id"=>$get['express_id'],
			"date_time"=>$get['date_time'],
			"getclass"=>$province_city_area,
			"addpage_info"=>$addpage_info,
			"parameter"=>$parameter
		);

		return $data;
	}

	/**
	 * 检查重复数据
	 */
	function check_repetition($item,$repetition_data){

		$repetition = 0;

		foreach($repetition_data as $data) {
			if ($data['id'] != $item['id']) {
				if (($item['package_detailed'] == $data['package_detailed']) AND ($item['order_phone'] == $data['order_phone'])) {
					$repetition = 1;
					break;
				}
			}
		}

		return $repetition;
	}

	/**
	 * 获取当前订单数据
	 */
	public function repetition_data(){

		//获取订单列表
		$where = array(
			"b.user_id"=>session('user.id')
		);

		$items = M("order")->alias("a")
			->join("LEFT JOIN __ADDPAGE_INFO__ b ON a.addpage_info_id = b.id LEFT JOIN __GOODS__ as c ON b.goods_id = c.id")
			->join("LEFT JOIN __ADDPAGE_PACKAGE__ d ON a.addpage_package_id = d.id")
			->join("LEFT JOIN __EXPRESS__ e ON a.express_id = e.id")
			->field("a.*,b.page_name,c.goods_name,d.package_price,e.express_name")->where($where)->order("a.id desc")->select();

		return $items;

	}

	/**
	 * 修改订单状态
	 */
	public function order_status(){

		$post = I("post.");

		$validate = true;

		foreach($post['list'] as $id){

			$where['id'] = array("eq",$id);

			$order_confirm = $this->order_confirm($id);

			if(!empty($order_confirm)){

				M("order")->where($where)->setField('order_state',$post['order_state']);

				//确认发货 - 发送短信
				$this->send_sms($id);

			}else{

				$validate = false;
				break;
			}

		}

		//订单状态
		$status_name = $this->get_state_name($post['order_state'],0);

		if($validate){
			$data = array(
				"code"=>200,
				"msg"=>$status_name
			);
		}else{
			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!"
			);
		}

		return $data;

	}

	/**
	 * 批量删除订单
	 */
	public function order_del(){

		$post = I("post.");

		$validate = true;

		foreach($post as $id){

			$where['id'] = array("eq",$id);

			$order_confirm = $this->order_confirm($id);

			if(!empty($order_confirm)){
				M("order")->where($where)->delete();
			}else{

				$validate = false;
				break;
			}

		}

		if($validate){
			$data = array(
				"code"=>200,
				"msg"=>"OK",
			);
		}else{
			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!",
			);
		}

		return $data;

	}

	/**
	 * 查询用户订单 所属该用户
	 */
	public function order_confirm($order_id){

		$where['a.id'] = array("eq",$order_id);
		$where['b.user_id'] = array("eq",session('user.id'));

		$items = M("order")->alias("a")->join("LEFT JOIN __ADDPAGE_INFO__ b ON a.addpage_info_id = b.id")->where($where)->getField("b.id");

		return $items;

	}

	/**
	 * 获取订单 - 备注信息
	 */
	public function order_remarks(){

		$order_id = I("post.id",'','int');

		$where['id'] = array("eq",$order_id);

		$items = M("order")->where($where)->getField("order_remarks");

		if(true){
			$data = array(
				"code"=>200,
				"msg"=>$items
			);
		}else{
			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!"
			);
		}

		return $data;

	}

	/**
	 * 更新订单 - 备注信息
	 */
	public function update_remarks(){

		$order_id = I("post.id",'','int');

		$content = I("post.content");

		$where['id'] = array("eq",$order_id);

		$order_confirm = $this->order_confirm($order_id);

		if(!empty($order_confirm)){

			M("order")->where($where)->setField('order_remarks',"$content");

			$data = array(
				"code"=>200,
				"msg"=>"OK"
			);

		}else{

			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!"
			);

		}

		return $data;

	}

	/**
	 * 获取订单数据
	 */
	public function order_data(){

		$id = I("post.id",'','int');

		//获取订单列表
		$where = array(
			"b.user_id"=>session('user.id'),
			"a.id"=>$id
		);

		$items = M("order")->alias("a")
			->join("LEFT JOIN __ADDPAGE_INFO__ b ON a.addpage_info_id = b.id LEFT JOIN __GOODS__ as c ON b.goods_id = c.id")
			->join("LEFT JOIN __ADDPAGE_PACKAGE__ d ON a.addpage_package_id = d.id")
			->join("LEFT JOIN __EXPRESS__ e ON a.express_id = e.id")
			->field("a.*,b.page_name,c.goods_name,d.package_price,e.express_name")->where($where)->find();

		if(!empty($items)){

			//订单来源
			$items['url'] = "http://".$_SERVER['HTTP_HOST'].U('Home/Mate/index',array("id"=>$items['addpage_info_id']));

			//查询套餐价格
			$items['total_price'] = $items['total_price'] ? $items['total_price'] : number_format($items['order_number'] * $items['package_price'],2);

			//获取省市区
			$items['city_area'] = $this->get_city_area($items['province_id']).'-'.$this->get_city_area($items['city_id']).'-'.$this->get_city_area($items['county_id']);

			if(!empty($items['county_id'])){
				$goods_class_id = $items['county_id'];
			}else if(!empty($items['city_id'])){
				$goods_class_id = $items['city_id'];
			}else if(!empty($items['province_id'])){
				$goods_class_id = $items['province_id'];
			}

			$items['goods_class_id'] = $goods_class_id;

			$items['code'] = 200;

			//订单状态
			$state_name = $this->get_state_name($items['order_state'],0);

			$items['state_name'] = $state_name;

			//快递地址
			$items['express_name'] = $this->get_state_name($items['express_id'],1);



		}else{
			$items['code'] = 400;
			$items['msg'] = "系统繁忙，请稍后重试!";
		}

		return $items;

	}

	/**
	 * 查询省市区数据
	 */
	public function get_city_area($id){

		if(!empty($id)){
			$items = M("province_city_area")->where("id=".$id)->getField("name");
		}else{
			$items = '';
		}

		return $items;

	}

	/**
	 * 查询省市区 所有关联ID
	 */
	public function get_area_pid($id,&$rows = array()){

		if(!empty($id)){

			$data = M("province_city_area")->field("id,pid,level")->where("id=".$id)->find();

			if($data['pid'] > 0){
				$rows[] = $data['pid'];
				$this->get_area_pid($data['pid'],$rows);
			}
		}else{
			$rows = array();
		}

		return $rows;
	}

	/**
	 * 编辑保存订单
	 */
	public function edit_save(){

		$post = I("post.");

		$city_area_data = $this->get_area_pid($post['goods_class_id']);

		$itmes = array(
			"package_detailed"=>$post['package_detailed'],
			"order_number"=>$post['order_number'],
			"total_price"=>$post['total_price'],
			"order_username"=>$post['order_username'],
			"province_id"=>$city_area_data[1],
			"city_id"=>$city_area_data[0],
			"county_id"=>$post['goods_class_id'],
			"order_address"=>$post['order_address'],
			"order_state"=>$post['order_state'],
			"express_id"=>$post['express_id'],
			"order_express_number"=>$post['order_express_number'],
			"order_message"=>$post['order_message'],
			"order_remarks"=>$post['order_remarks'],
			"order_phone"=>$post['order_phone'],
		);

		M("order")-> where('id='.$post['id'])->setField($itmes);

		//确认发货 - 发送短信
		$this->send_sms($post['id']);

		//订单状态
		$state_name = $this->get_state_name($post['order_state'],0);

		//快递地址
		$express_name = $this->get_state_name($post['express_id'],1);

		if(true){
			$data = array(
				"code"=>200,
				"msg"=>"请求成功",
				"state_name"=>$state_name,
				"express_name"=>$express_name
			);
		}else{
			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!",
			);

		}
		return $data;
	}

	/**
	 * 无限级获取 - 获取省市区
	 */
	public function city_area($goods_list,$pid = 0){

		$rows = array();

		foreach($goods_list as $k=>$list){

			if($list['pid'] == $pid){
				$list['_data'] = $this->city_area($goods_list,$list['id']);
				$rows[] = $list;
			}
		}

		return $rows;

	}

	/**
	 * 新增订单
	 */
	public function add_order(){

		$post = I("post.");

		$order_sn = D('Home/Mate')->getrandomstring(2).date("dHis",time()).$post['addpage_info_id']."0".rand(0,9);
		$city_area_data = $this->get_area_pid($post['goods_class_id']);

		$items = array(
			"order_sn"=>$order_sn,
			"package_detailed"=>$post['package_detailed'],
			"order_number"=>$post['order_number'],
			"total_price"=>$post['total_price'],
			"order_username"=>$post['order_username'],
			"order_phone"=>$post['order_phone'],
			"order_username"=>$post['order_username'],
			"order_address"=>$post['order_address'],
			"order_message"=>$post['order_message'],
			"order_create_time"=>date("Y-m-d H:i:s",time()),
			"order_state"=>0,
			"express_id"=>1,
			"province_id"=>$city_area_data[1],
			"city_id"=>$city_area_data[0],
			"county_id"=>$post['goods_class_id'],
			"addpage_info_id"=>$post['addpage_info_id'],
		);

		$M = M("order");
		$M->startTrans();//开启事务
		$data = array();
		$id = $M->data($items)->add();
		if($id)
		{
			$data['code'] = 200;
			$data['msg'] = "OK";
			$M->commit();//提交事务成功
		}else{
			$data['code'] = 400;
			$data['msg'] = "系统繁忙，请稍后重试!";
			$M->rollback();//事务有错回滚
		}

		return $data;

	}

	/**
	 * 下载订单XLS 表格
	 */
	public function download_xls(){

		$get = I("get.");

		//获取订单列表
		$where = array(
			"b.user_id"=>session('user.id')
		);

		//搜索关键词
		if(!empty($get['start_time']) && !empty($get['end_time'])){
			$start_time = $get['start_time']." 00:00:00";
			$end_time = $get['end_time']." 23:59:59";
			$where['a.order_create_time'] = array(array('ELT',$start_time),array('EGT',$end_time),"AND");
		}

		if(!empty($get['keyword'])){
			switch($get['pattern']){
				case 0:
					$where['a.order_phone'] = array('eq',$get['keyword']);
					break;
				case 1:
					$where['a.order_sn'] = array('eq',$get['keyword']);
					break;
				case 2:
					$where['b.goods_id'] = array('eq',$get['keyword']);
					break;
				case 3:
					$where['b.page_name'] = array('like',"%".$get['keyword']."%");
					break;
				case 4:
					$where['b.id'] = array('eq',$get['keyword']);
					break;
				case 5:
					$where['d.package_name'] = array('like',"%".$get['keyword']."%");
					break;
				case 6:
					$where['a.order_address'] = array('like',"%".$get['keyword']."%");
					break;
			}
		}

		if(!empty($get['order_state'])){
			$where['a.order_state'] = array('eq',$get['order_state']);
		}

		if(!empty($get['express_id'])){
			$where['a.express_id'] = array('eq',$get['express_id']);
		}

		$items = M("order")->alias("a")
			->join("LEFT JOIN __ADDPAGE_INFO__ b ON a.addpage_info_id = b.id LEFT JOIN __GOODS__ as c ON b.goods_id = c.id")
			->join("LEFT JOIN __ADDPAGE_PACKAGE__ d ON a.addpage_package_id = d.id")
			->join("LEFT JOIN __EXPRESS__ e ON a.express_id = e.id")
			->field("a.*,b.page_name,c.goods_name,d.package_price,e.express_name")->where($where)->order("a.id desc")->select();

		$data = array();

		foreach($items as $k=>$itme){
			$data[$k]['order_sn'] = $itme['order_sn'];
			$data[$k]['page_name'] = $itme['page_name'];
			$data[$k]['package_detailed'] = $itme['package_detailed'];
			$data[$k]['order_number'] = $itme['order_number'];
			$data[$k]['package_price'] = number_format($itme['package_price'],2);
			$data[$k]['total_price'] = $itme['total_price'];
			$data[$k]['order_username'] = $itme['order_username'];
			$data[$k]['order_phone'] = $itme['order_phone'];
			$data[$k]['province_id'] = $this->get_city_area($itme['province_id']);
			$data[$k]['city_id'] = $this->get_city_area($itme['city_id']);
			$data[$k]['county_id'] = $this->get_city_area($itme['county_id']);
			$data[$k]['order_address'] = $itme['order_address'];
			$data[$k]['order_ip'] = $itme['order_ip'];
			$data[$k]['order_create_time'] = $itme['order_create_time'];
			$data[$k]['state_name'] = $this->get_state_name($itme['order_state'],0);
			$data[$k]['express_name'] = $this->get_state_name($itme['express_id'],1);
			$data[$k]['order_express_number'] = $itme['order_express_number'];
			$data[$k]['order_message'] = $itme['order_message'];
			$data[$k]['order_remarks'] = $itme['order_remarks'];
			$data[$k]['url'] = "http://".$_SERVER['HTTP_HOST'].U('Home/Mate/index',array("id"=>$itme['addpage_info_id']));
		}

		return $data;
	}

	public function get_state_name($id,$typeid=0){

		if($typeid == 0){

			//订单状态名称
			if($id == 0){
				$name = '待确认';
			}else if($id == 1){
				$name = '待发货';
			}else if($id == 2){
				$name = '已发货';
			}else if($id == 3){
				$name = '已签收';
			}else if($id == 4){
				$name = '已退货';
			}else if($id == 5){
				$name = '售后处理';
			}else if($id == 6){
				$name = '确认假单';
			}else if($id == 7){
				$name = '取消订单';
			}else{
				$name = '待确认';
			}

		}else{

			//快递地址
			$name = M("express")->where("id=".$id)->getField("express_name");
		}

		return $name;

	}


	/**
	 * 订单 - 批量发货
	 */
	public function import_excel(){

		if (IS_POST) {

			//生成用户目录
			$user_directory = crypt(session('user.id'),"File");

			$config = array(
				'maxSize' => 52428800,
				'savePath' =>$user_directory.'/',
				'rootPath'     => './Upload/excel/',
				'saveName' => array('uniqid', ''),
				'exts' => array('xls'),
				'autoSub' => true,
				'subName' => array('date', 'Ymd'),
			);

			$upload = new \Think\Upload($config);

			$info = $upload->upload();

			if (!$info) {

				$data = array(
					"code"=>401,
					"msg"=>"上传失败,请检查文件格式或文件大小!"
				);

			} else {

				$src = ['src' => $info['file']['savepath'] . $info['file']['savename']];

				$file_data = import_excel('./Upload/excel/'.$src['src']);

				//验证模板
				$validation_template = false;

				$template = array('订单ID','页面名称','套餐明细','数量','套餐单价','总价','姓名','手机号码','省','市','地区','收件地址','下单IP','下单时间','订单状态','快递公司','快递单号','留言','备注','详情URL');

				foreach($file_data[1] as $k=>$name){
					if($template[$k] != $name){
						$validation_template = true;
						break;
					}
				}

				if($validation_template){

					$data = array(
						"code"=>401,
						"msg"=>"数据格式错误，请参考下载的模板文件"
					);

				}else{

					//获取当前用户 - 订单列表
					$addpage_info = M("addpage_info")->field("id")->where("user_id=".session('user.id'))->select();

					foreach($addpage_info as $info){
						$addpage_info_id[] = $info['id'];
					}

					foreach($file_data as $k=>$data){

						if($k > 1 && !empty($data[0])){

							if($data[14] == "待确认"){
								$order_state = 0;
							}else if($data[14] == "待发货"){
								$order_state = 1;
							}else if($data[14] == "已发货"){
								$order_state = 2;
							}else if($data[14] == "已签收"){
								$order_state = 3;
							}else if($data[14] == "已退货"){
								$order_state = 4;
							}else if($data[14] == "售后处理"){
								$order_state = 5;
							}else if($data[14] == "确认假单"){
								$order_state = 6;
							}else if($data[14] == "取消订单"){
								$order_state = 7;
							}else{
								$order_state = 8;
							}

							$map['express_name'] = array('like',"%".$data[15]."%");
							$express_id = M("express")->where($map)->getField("id");

							if($order_state < 8){
								$items['order_state'] = $order_state;
							}

							if(!empty($express_id)){
								$items['express_id'] = $express_id;
							}

							if(!empty($data[16])){
								$items['order_express_number'] = $data[16];
							}

							if(!empty($items) && !empty($addpage_info_id)){
								$where['addpage_info_id'] = array("in",$addpage_info_id);
								$where['order_sn'] = array("eq",$data[0]);

								M("order")-> where($where)->setField($items);

								//批量邮件发送
								$order_list = M("order")->field("id")->where($where)->select();

								foreach($order_list as $list){
									$this->send_sms($list['id']);
								}

							}

						}

					}

					$filename = "订单列表".date("Y-m-d",time())."xls 上传成功";

					$data = array(
						"code"=>200,
						"msg"=>$filename
					);

				}

			}


		} else {

			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!"
			);

		}

		return $data;

	}

	/**
	 * 订单修改短信发送
	 */
	public function send_sms($order_id){

		//发送短信
		$info = M("order")->field("id,order_phone,order_state,order_express_number,is_sms,addpage_package_id,addpage_info_id,order_sn,express_id")->where('id='.$order_id)->find();

		//获取查询套餐名称
		if(!empty($info['addpage_package_id'])){
			$package_name = M("addpage_package")->where("id=".$info['addpage_package_id'])->getField("package_name");
		}else{
			$package_name = '';
		}

		//查询快递公司
		$express_name = $this->get_state_name($info['express_id'],1);

		//获取产品信息
		$as_phone = M("addpage_info")->where("id=".$info['addpage_info_id'])->getField("as_phone");

		//发送已收货短信
		if(($info['order_state'] == 2) && strlen($info['order_express_number']) > 0 && ($info['is_sms'] == 0)){

			//生成商品链接
			$url = "http://".$_SERVER['HTTP_HOST'].U('Home/Mate/index',array('id'=>$info['id']));

			$content = '您的订单已成功提交（'.$package_name.'，订单编号：'.$info['order_sn'].'）已由'.$express_name.'(快递单号:'.$info['order_express_number'].')发货,请注意查收。商品页面:'.$url.' 。如需帮助请联系客服：'.$as_phone.' 【众云电商】';

			$sms = send_sms($info['order_phone'],$content);

			//写入日志
			if($sms['code'] == 200){
				M("order")->where('id='.$order_id)->setField('is_sms',1);
			}else{
				\Think\Log::record($sms['msg']);
			}
		}

	}


}
